#include "dlgclock.h"
#include "item.h"
#include <QDebug>
DlgClock::DlgClock(QWidget *parent, int restTime,QPushButton * button):QLCDNumber(parent)
{
    this->restTime=restTime;
    renderClock();
    setWindowFlags(Qt::FramelessWindowHint);	//(b)
    setWindowOpacity(0.8);
    timer=new QTimer(this);//新建计时器
    connect(timer,SIGNAL(timeout()),this,SLOT(updateClock()));
    timer->start(1000);
    resize(240,150);
    setDigitCount(8);
    this->button=button;
    updateClock();
    qDebug()<<"调用构造函数";
}

void DlgClock::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton)
    {
        dragPosition=event->globalPos()-frameGeometry().topLeft();
        event->accept();
    }
    if(event->button()==Qt::RightButton)
    {
        if(button!=0)
            button->setEnabled(true);//恢复按钮可用
        timer->stop();
        close();
    }
}

void DlgClock::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons()&Qt::LeftButton)
    {
        move(event->globalPos()-dragPosition);
        event->accept();
    }
}

void DlgClock::updateClock()
{
    QTime temp(0,0,0),time;
    time=temp.addSecs(restTime);
    QString text=time.toString("hh:mm:ss");

    /*渲染颜色*/
    renderClock();
    if(restTime<0)//如果时间计算小于0
    {
        timer->stop();//停止计时
        QMessageBox::information(this,"提示","时间已到",QMessageBox::Ok);
        close();
        return;
    }
    /*进行渲染*/
    restTime--;
    display(text);
}

void DlgClock::renderClock()
{
    //value 0~512 0为纯红色，512为纯蓝色
    /*设置初始背景*/
    QColor color;
    int value;
    if(restTime<=60)
    {
        value=restTime;
    }
    else if(restTime<=25200)
    {
        value=restTime/60+60;
    }
    else if(restTime<=82800)
    {
        value=restTime/1800+480;
    }
    else
    {
        value=512;
    }
    value=value<0?0:(value>255)?255:value;
    color.setRgb(value>255?512-value:255-value,0,value>255?value-255:value);
    QPalette p;
    p.setColor(QPalette::Window,color);
    setPalette(p);
}
